<script setup lang="ts">
import { computed, shallowRef, watch } from 'vue';
import { $t } from '@/locales';
import { fetchGetAllPermissions, fetchGetCheckedButtonByRole, fetchUpdateRole } from '@/service/api';

defineOptions({
  name: 'ButtonAuthModal'
});

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

function closeModal() {
  visible.value = false;
}

const title = computed(() => $t('common.edit') + $t('page.manage.role.buttonAuth'));

type ButtonConfig = {
  id: string;
  desc: string;
  code: string;
  i18nKey?: App.I18n.I18nKey;
  children?: ButtonConfig[];
};

const tree = shallowRef<ButtonConfig[]>([]);

const setI18nDesc = (data: ButtonConfig[]) => {
  const result = data.map(item => {
    const { id, desc, code, i18nKey } = item;
    const tempResult: ButtonConfig = {
      id,
      code,
      desc: i18nKey ? $t(i18nKey) : desc
    };
    if (item.children?.length) {
      tempResult.children = setI18nDesc(item.children);
    }
    return tempResult;
  });
  return result;
};

async function getAllButtons() {
  // request
  const { error, data } = await fetchGetAllPermissions();
  if (!error) {
    tree.value = setI18nDesc(data);
  }
}

const checks = shallowRef<number[]>([]);

async function getChecks() {
  // request
  const { data, error } = await fetchGetCheckedButtonByRole(props.roleId);
  if (!error) {
    checks.value = data;
  }
}

async function handleSubmit() {
  // request
  const { error } = await fetchUpdateRole({
    id: props.roleId,
    buttons: checks.value
  });
  if (error) {
    return;
  }
  window.$message?.success?.($t('common.modifySuccess'));

  closeModal();
}

function init() {
  getAllButtons();
  getChecks();
}

watch(visible, newVal => {
  if (newVal) {
    init();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-480px">
    <NTree
      v-model:checked-keys="checks"
      :data="tree"
      key-field="id"
      label-field="desc"
      :selectable="false"
      default-expand-all
      check-strategy="child"
      block-line
      cascade
      checkable
      expand-on-click
      virtual-scroll
      class="h-280px"
    />
    <template #footer>
      <NSpace justify="end">
        <NButton size="small" class="mt-16px" @click="closeModal">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" size="small" class="mt-16px" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
